package com.example.yls.demoa;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyService extends Service  {
    Boolean isLive=true;



    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("Myservice","Thread id="+Thread.currentThread().getId());
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isLive){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Intent intent=new Intent();
                intent.setAction("TIME_CHANGE");
                intent.putExtra("time",getTimeStr());
                sendBroadcast(intent);}
            }


        }).start();
    }
    private String getTimeStr() {
        Date date=new Date();
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return dateFormat.format(date);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isLive=false;
    }
}
